<template>
  <div >
    <el-form :model="registryForm" status-icon :rules="rules" ref="registryForm" class="login-form" autocomplete="on" label-position="left">
        <el-form-item label="用户：" prop="username">
            <el-input type="username" v-model="registryForm.username" ></el-input>
        </el-form-item>
        <el-form-item label="昵称：" prop="nickname">
            <el-input type="nickname" v-model="registryForm.nickname" ></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="password">
            <el-input type="password" v-model="registryForm.password" ></el-input>
        </el-form-item>
        <el-form-item label="确认：" prop="checkPass">
            <el-input type="password" v-model="registryForm.checkPass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm('registryForm')">提交</el-button>
            <el-button @click="resetForm('registryForm')">重置</el-button>
        </el-form-item>
    </el-form>
  </div>
</template>

<script>
// import openWindow from '@/utils/open-window'
import { registUser } from '@/api/user'
export default {
  name: 'Registry',
 data() {
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.registryForm.checkPass !== '') {
            this.$refs.registryForm.validateField('checkPass');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.registryForm.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        registryForm: {
          username: '',
          nickname: '',
          password: '',
          checkPass: ''
        },
        rules: {
          username: [{ required: true, trigger: 'blur'}],
          nickname: [{ required: true, trigger: 'blur'}],
          password: [
            {  required: true, validator: validatePass, trigger: 'blur' }
          ],
          checkPass: [
            {  required: true, validator: validatePass2, trigger: 'blur' }
          ]
        }
      };
    },
    methods: {
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            alert('submit!');
            registUser(this.registryForm).then(response => {
                this.$notify({
                title: 'Success',
                message: 'Created Successfully',
                type: 'success',
                duration: 2000
                })
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    }
  }
</script>
